package com.smedi.ismedi.constructionproject.core.port.adapter.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.smedi.ismedi.authoritymanagement.api.dto.response.RoleBasicResponse;
import com.smedi.ismedi.authoritymanagement.api.feign.RemoteAuthorityRoleManagementFeignApi;
import com.smedi.ismedi.constructionproject.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.constructionproject.core.port.adapter.service.AuthorityAccessRemoteApiService;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class AuthorityAccessRemoteApiServiceImpl implements AuthorityAccessRemoteApiService {

    private final RemoteAuthorityRoleManagementFeignApi remoteAuthorityRoleManagementFeignApi;

    @Override
    public String queryRoleNameByPersonId(Long personId) {
        ResponseData<List<RoleBasicResponse>> roleBasicResponse = remoteAuthorityRoleManagementFeignApi.getQueryRolesByPersonId(personId);
        if (!roleBasicResponse.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, roleBasicResponse.getApplication(), String.valueOf(roleBasicResponse.getErrorMsg()));
        }
        List<String> roleNameList = new ArrayList<>();
        for (RoleBasicResponse i : roleBasicResponse.getData()) {
            roleNameList.add(i.getRoleName());
        }

        String roleNames = StringUtils.join(roleNameList, ",");
        return roleNames;
    }

    @Override
    public List<Long> getQueryAllPersonIdsByRoleId(String roleName) {
        ResponseData<List<RoleBasicResponse>> responseData = remoteAuthorityRoleManagementFeignApi.getQueryAllPersonIdsByRoleId(roleName, false, true);
        if (!responseData.isSuccess()) {
            throw LogicException.raise(CustomError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
        if (CollectionUtils.isNotEmpty(responseData.getData())){
            return responseData.getData().get(0).getRoleOwnerPersonIds();
        }
        return new ArrayList<>();
    }

}
